﻿using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE80;
using EnvDTE;
using TSVNAddin.SVN;
using System.IO;

namespace TSVNAddin.Core
{
	public class EventDispatcher
	{
		private readonly SolutionEvents _SolutionEvents;
		private readonly ProjectItemsEvents _ProjectItemsEvents;

		private readonly List<ISolutionEventListener> _SolutionEventListeners = new List<ISolutionEventListener>();
		private readonly List<IProjectEventListener> _ProjectEventListeners = new List<IProjectEventListener>();
		private readonly List<IItemEventListener> _ItemEventListeners = new List<IItemEventListener>();

		public EventDispatcher(SolutionEvents solutionEvents, ProjectItemsEvents projectItemsEvents)
		{
			_SolutionEvents = solutionEvents;
			_SolutionEvents.Renamed += SolutionRenamed;
			_SolutionEvents.Opened += SolutionOpened;
			_SolutionEvents.ProjectAdded += ProjectAdded;
			_SolutionEvents.ProjectRemoved += ProjectRemoved;
			_SolutionEvents.ProjectRenamed += ProjectRenamed;

			_ProjectItemsEvents = projectItemsEvents;
			_ProjectItemsEvents.ItemAdded += ItemAdded;
			_ProjectItemsEvents.ItemRemoved += ItemRemoved;
			_ProjectItemsEvents.ItemRenamed += ItemRenamed;
		}

		void SolutionOpened()
		{
			_SolutionEventListeners.ForEach(listener => listener.NotifyOpened());
		}

		public void AddSolutionEventListener(ISolutionEventListener solutionEventListener)
		{
			_SolutionEventListeners.Add(solutionEventListener);
		}

		public void AddProjectEventListener(IProjectEventListener projectEventListener)
		{
			_ProjectEventListeners.Add(projectEventListener);
		}

		public void AddItemEventListener(IItemEventListener itemEventListener)
		{
			_ItemEventListeners.Add(itemEventListener);
		}


		void SolutionRenamed(string oldName)
		{
			_SolutionEventListeners.ForEach(listener => listener.NotifyRenamed(oldName));
		}

		void ProjectAdded(Project project)
		{
			_ProjectEventListeners.ForEach(listener => listener.NotifyAdded(project));
		}

		void ProjectRemoved(Project project)
		{
			_ProjectEventListeners.ForEach(listener => listener.NotifyRemoved(project));
		}

		void ProjectRenamed(Project project, string oldName)
		{
			_ProjectEventListeners.ForEach(listener => listener.NotifyRenamed(project, oldName));
		}

		void ItemAdded(ProjectItem projectItem)
		{
			_ItemEventListeners.ForEach(listener => listener.NotifyAdded(projectItem));
		}

		void ItemRemoved(ProjectItem projectItem)
		{
			_ItemEventListeners.ForEach(listener => listener.NotifyRemoved(projectItem));
		}

		void ItemRenamed(ProjectItem projectItem, string oldName)
		{
			_ItemEventListeners.ForEach(listener => listener.NotifyRenamed(projectItem, oldName));
		}
	}
}
